﻿using System;
using UnityEditor;

using UnityEngine;

namespace Yoozoo.UI.YGUI.Utility
{
    public class PrefabStageProcessor
    {
        [InitializeOnLoadMethod]
        static void Initialize()
        {
            UnityEditor.SceneManagement.PrefabStage.prefabStageOpened += OnPrefabStageOpened;
            UnityEditor.SceneManagement.PrefabStage.prefabSaving += OnPrefabSaving;
        }

        static void OnPrefabSaving(GameObject contentsRoot)
        {
            var images = contentsRoot.GetComponentsInChildren<YImage>(true);
            foreach (var image in images)
            {
                if (image && image.sprite && image.clearOnSave)
                {
                    AssetDatabase.TryGetGUIDAndLocalFileIdentifier(image.sprite, out string guid, out long localId);
                    string spritePath = AssetDatabase.GUIDToAssetPath(guid);
                    //Debug.LogFormat("后处理UI: {0} sprite {1} guid: {2}", image.name, spritePath, guid);
                    if (spritePath.StartsWith("Assets"))
                    {
                        image.spriteGuid = guid;
                    }

                    image.sprite = null;
                }
            }
        }

        static void OnPrefabStageOpened(UnityEditor.SceneManagement.PrefabStage prefabStage)
        {
            //Debug.Log("OnPrefabStageOpened " + prefabStage.prefabAssetPath);

            var contentsRoot = prefabStage.prefabContentsRoot;
            var images = contentsRoot.GetComponentsInChildren<YImage>(true);
            foreach (var image in images)
            {
                if (image.clearOnSave && image.sprite == null && !string.IsNullOrEmpty(image.spriteGuid))
                {
                    string path = AssetDatabase.GUIDToAssetPath(image.spriteGuid);
                    image.sprite = AssetDatabase.LoadAssetAtPath<Sprite>(path);
                }
            }
        }
    }
}
